#include "ParasolidWriter.hpp"
#include "psw/psw.hpp"
#include <iostream>
#include "common/logger.h"

namespace  AMCAX::Exchange {

    Dtk_ErrorStatus ParasolidWriter::WriteInit(Dtk_string dumpFile, const Dtk_string& outputFile)
    {
        return WriteInit(dumpFile, outputFile, 0);
    }

    Dtk_ErrorStatus ParasolidWriter::WriteInit(Dtk_string dumpFile, const Dtk_string& outputFile, int option)
    {
        m_outputFileName = outputFile;
        std::cout << "Output file is : " << m_outputFileName << std::endl;

        Dtk_bool muteMode = DTK_TRUE;  //  no log write
        DtkErrorStatus status = psw_InitFile( m_outputFileName, muteMode );

        if( status != dtkNoError )
        {
            std::cout << "error : " << dtkTypeError( status ).c_str() << std::endl;
            return status;
        }

        return dtkNoError;
    }

    Dtk_ErrorStatus ParasolidWriter::WriteEnd()
    {
        Dtk_tab<Dtk_ID> returnID;
        auto status = psw_EndFile( returnID );
        if( status != dtkNoError )
        {
            std::cout << "error : " << dtkTypeError( status ).c_str() << std::endl;
        }
        else
            std::cout << "=> " << m_outputFileName.c_str() << std::endl;

        return status;
    }

    void ParasolidWriter::WriteMesh(Dtk_MeshPtr& inMeshToWrite, Dtk_tab<Dtk_ID>& outIds)
    {
        Dtk_tab<Dtk_ID> outTabIds;
        auto status = psw_WriteMesh(inMeshToWrite, outTabIds);
        if (status != dtkNoError)
        {
            LOG_ERROR("WriteMesh failed with error {}", (int)status);
        }

        for (auto id : outTabIds)
        {
            outIds.push_back(id);
        }

    }

    void ParasolidWriter::WriteBody(Dtk_BodyPtr& inBody, Dtk_tab<Dtk_ID>& outIds)
    {
        Dtk_tab<Dtk_ID> outTabIds;
        auto status = psw_WriteBody(inBody, outTabIds);
        if (status != dtkNoError)
        {
            LOG_ERROR("WriteBody failed with error {}", (int)status);
            return;
        }

        std::cout << "Write body >> " << inBody->GetID() << std::endl;
        for (auto id : outTabIds)
        {
            outIds.push_back(id);
            std::cout << inBody->GetID() << " - Result body >> " << id << std::endl;
        }    
    }

    Dtk_ErrorStatus ParasolidWriter::CreateAssembly(Dtk_ComponentPtr inComponent, Dtk_ID& outAssemblyId)
    {
        auto status = psw_CreateEmptyAssembly( outAssemblyId );
        return status;
    }

    
    Dtk_ErrorStatus ParasolidWriter::CreateInstance(Dtk_ID inAssemblyId, Dtk_ID inPrototypeId, Dtk_transfoPtr matrix, Dtk_ID& outIdInst)
    {
        auto status = psw_CreateInstance( inAssemblyId, inPrototypeId, matrix, outIdInst);
        return status;
    }

}
